import {
  registerMicroApps,
  start,
  addGlobalUncaughtErrorHandler,
} from "qiankun";
import setting from "@/settings";
import { Loading } from "element-ui";
import { qiankunState } from "@/qiankun-main/globalState";
import store from "@/store";
import router from "@/router";
import Vue from "vue";

// 处理路由的path
function getRouterPath(arg) {
  const [params, modules] = arg;
  let opt = {};
  if (typeof params === "string") {
    opt.path = params;
    opt.modules = modules || "";
  } else {
    opt = { ...params };
  }
  if (opt.path) {
    if (!opt.path.startsWith("/")) {
      opt.path = `/${opt.path}`;
    }
    if (modules && !opt.path.startsWith("/modules/")) {
      opt.path = `/modules/${modules}/${modules}${opt.path}`;
    }
  }
  return opt;
}

// 重写路由 主要修改path
const mainRouter = {
  push: (...params) => {
    const opt = getRouterPath(params);
    router.push(opt);
  },
  replace: (path) => {
    const opt = getRouterPath(path);
    router.replace(opt);
  },
  go: (n) => {
    router.go(n);
  },
};
let loadFull;
export const registerApps = () => {
  require("./style.less");
  const subRoutes = Vue.prototype._.cloneDeep(
    store.state.permission.subRoutes || {}
  );
  registerMicroApps(
    setting.microApps.map((item) => {
      const activeRule = "/modules/" + item.name;
      return {
        ...item,
        entry:
          process.env.NODE_ENV === "production" ? activeRule + "/" : item.entry,
        container: "#qiankunChildContainer",
        activeRule,
        props: {
          // 系统token
          token: store?.state?.user?.token,
          // 基础路由 暂时没用到
          routerBase: activeRule,
          // main包路由
          $router: mainRouter,
          // main包数据
          $store: store,
          // 子包的路由 传给子包
          subRoutes: subRoutes[item.name] || [],
          // 全局数据
          globalState: qiankunState,
        },
        loader: (loading) => {
          if (loading) {
            loadFull = Loading.service({
              fullscreen: true,
              body: true,
              lock: true,
              text: "拼命加载中...",
              spinner: "el-icon-loading",
              background: "rgba(0, 0, 0, 0.4)",
              customClass: "qiankun-body-loading",
            });
          } else {
            loadFull.close();
          }
        },
      };
    })
  );
  start();
};
addGlobalUncaughtErrorHandler(() => {
  loadFull && loadFull.close();
});
